<template>
    <div style="background: white">

        <mai-mao-tabs :font-size=13 :width=200 :tabs="orderTab" :active-tab="activeTab"
                      @activeTabChange="orderTabChange"></mai-mao-tabs>
        <div>
            <div>
                <a-input-search style="width: 500px" placeholder="订单号" v-model="searchData.orderId" size="default"
                                @search="loadGroup">

                </a-input-search>
                <a-button type="link" @click="simpleSearch=!simpleSearch">{{simpleSearch?'更多搜索条件':'精简搜索条件'}}</a-button>
            </div>
            <a-form-model v-show="!simpleSearch" layout="inline">

                <a-row>

                    <a-col :span="8">
                        <a-form-model-item label="商品名：">
                            <a-input v-model="searchData.title"/>
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-model-item label="店铺名：">
                            <a-input v-model="searchData.shopName"/>
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-model-item label="交易状态：">
                            <a-select v-model="searchData.status" defaultValue="-1" style="width: 190px"
                                      @change="loadGroup">
                                <a-select-option value=null>全部</a-select-option>
                                <a-select-option value="1">等待买家付款</a-select-option>
                                <a-select-option value="2">买家已支付</a-select-option>
                                <a-select-option value="3">部分发货</a-select-option>
                                <a-select-option value="4">全部发货</a-select-option>
                                <a-select-option value="5">交易成功</a-select-option>
                                <a-select-option value="6">交易关闭</a-select-option>
                                <a-select-option value="7">退款中的订单</a-select-option>
                            </a-select>
                        </a-form-model-item>
                    </a-col>

                </a-row>
                <a-row>
                    <a-col :span="16">
                        <a-form-model-item label="成交时间：">
                            <a-date-picker
                                    v-model="searchData.fromTime"
                                    show-time
                                    :disabled-date="disabledStartDate"
                                    format="YYYY-MM-DD HH:mm:ss"
                                    placeholder="请选择时间范围起始"
                                    @change="fromTimeChange"
                            />
                            -
                            <a-date-picker
                                    v-model="searchData.toTime"
                                    show-time
                                    :disabled-date="disabledEndDate"
                                    @change="toTimeChange"
                                    format="YYYY-MM-DD HH:mm:ss"
                                    placeholder="请选择时间范围起始"
                            />
                        </a-form-model-item>
                    </a-col>
                    <a-col :span="8">
                        <a-form-model-item label="评价状态：">
                            <a-select v-model="searchData.commentType" defaultValue="-1" style="width: 190px"
                                      @change="loadGroup">
                                <a-select-option value=null>全部</a-select-option>
                                <a-select-option value="0">待评价</a-select-option>
                                <a-select-option value="1">已评价</a-select-option>
                            </a-select>
                        </a-form-model-item>
                    </a-col>

                </a-row>
                <a-button style="color: #E2231A" @click="loadGroup">搜索</a-button>
                <a-button type="danger" @click="exportOrder">导出当前订单</a-button>
                <span style="font-size: 11px;color: red">订单导出数据有延迟，如与当前数据不同步，请等待5分钟...</span>


            </a-form-model>
        </div>
        <div>
            <div class="table-header">
                <a-row>
                    <a-col :span="4" offset="3">宝贝</a-col>
                    <a-col :span="2" offset="3">单价</a-col>
                    <a-col :span="2" offset="0">数量</a-col>
                    <a-col :span="3">实付款</a-col>
                    <a-col :span="3">交易状态</a-col>
                    <a-col :span="2">订单类型</a-col>
                    <a-col :span="2">操作</a-col>
                </a-row>
            </div>
            <a-card style="padding: 0" hoverable v-for="orderShop in orderData" class="order-card">

                <div style="padding-bottom: 15px">
                    <span class="order-shop-top" style="font-weight: 700">{{orderShop.createTime}}</span>
                    <span class="order-shop-top"> 订单号：{{orderShop.orderId}}</span>
                    <span class="order-shop-top shopName" style="margin-left: 40px">
                        <a-icon type="shop" theme="twoTone" style="margin-right: 10px;font-size: 16px;"
                                twoToneColor="#C30601"/>
                        <a class="shopName">{{orderShop.shopName}}</a>
                      </span>
                    <span style="float:right;">
                        <span v-if="orderShop.status===1||orderShop.status===5||orderShop.status===6" class="delete-btn"
                              @click="deleteOrder(orderShop)"><a-icon type="delete"/></span>
                    </span>
                </div>

                <div v-for="(goods,goodsIndex) in orderShop.orderGoodsList" style="width: 100%" class="order-item">
                    <a-row>
                        <a-col :span="3">
                            <img style="width: 80px;height: 80px"
                                 :src="goods.picture"/>
                        </a-col>

                        <a-col :span="6">
                            <div class="goods-title">
                                <span @click="toGoodsDetail(goods)"> {{goods.title}} [交易快照]</span>
                            </div>

                            <div class="goods-spec">
                                {{goods.specDisplayName}}
                            </div>
                        </a-col>
                        <a-col :span="2" offset="1">
                            ￥ {{goods.price}}
                        </a-col>
                        <a-col :span="1" offset="0">x{{goods.num}}</a-col>
                        <a-col :span="3" offset="0" style="text-align: center">
                            <div>
                                <span style="text-decoration: line-through;color: #afafaf">￥{{orderShop.totalPrice}}</span>
                            </div>
                            <span style="font-weight: 800">￥{{orderShop.actualPrice}}</span>
                            <div>
                                <span style="font-size: 12px;color: #6C6C6C">含运费：(￥{{orderShop.deliveryFee}})</span>
                            </div>
                        </a-col>
                        <a-col :span="3" offset="1">
                            <a-tag color="blue" style="margin-bottom: 10px">
                                {{orderShop.status===1?'待付款':orderShop.status===2?'已付款':orderShop.status===5?'交易成功':orderShop.status===6?'交易取消':goods.receive===true?'':'交易中'}}
                            </a-tag>
                            <br/>
                            <a-tag color="green" style="margin-bottom: 10px">
                                {{goods.shippedStatus===1&&goods.receive===true?'已收货':goods.shippedStatus===1?'已发货':goods.shippedStatus===0?'未发货':'交易异常'}}
                            </a-tag>
                            <a-tag color="orange" v-if="orderShop.status===5">
                                {{goods.comment===true?'已评论':'未评论'}}
                            </a-tag>
                        </a-col>
                        <a-col :span="2" >
                            <a-tag :color="orderShop.type===1?'blue':orderShop.type===2?'red':''" >
                                {{orderShop.type===1?'普通订单':orderShop.type===2?'秒杀订单':'------'}}
                            </a-tag>
                        </a-col>
                        <a-col :span="2">
                            <div>

                                <a-button type="link" v-if="orderShop.status===5&&goods.comment===false"
                                          @click="pubComment(goods)">去评论
                                </a-button>
                                <a-button type="link" style="color: #E2231A"
                                          v-if="goods.shippedStatus===1&&goods.receive===false"
                                          @click="reveiveGoods(goods)">确认收货
                                </a-button>
                                <a-button v-if="orderShop.status===5||orderShop.status===6" @click="buyAgain">再次购买
                                </a-button>

                                <a-button style="font-size: 14px" type="link"
                                          v-if="(orderShop&&orderShop.status===1)"
                                          @click="toPay(orderShop)">付款
                                </a-button>
                            </div>
                        </a-col>
                    </a-row>
                    <a-divider v-if="goodsIndex!=orderShop.orderGoodsList.length-1"></a-divider>
                </div>

            </a-card>
            <a-pagination style="float:right;" showQuickJumper v-model="pageMap.page" :page-size="pageMap.size"
                          :total="pageMap.total" @change="pageChange"/>

        </div>


    </div>
</template>

<script>
    import XEUtils from 'xe-utils'
    import {isArr} from "../../../utils/arrayUtil"
    import {getLocalStorageJson, setLocalStorageJson} from "../../../utils/auth";
    import orderApi from "../../../api/order/orderApi";
    import moment from "moment-timezone";
    import MaiMaoTabs from "../../../components/common/MaiMaoTabs";

    export default {
        name: "cartIndex",
        components: {MaiMaoTabs},
        inject: ["reload"],
        data() {
            return {
                orderData: [],
                pageMap: {
                    page: 1,
                    size: 8,
                    total: 0
                },
                searchData: {
                    orderId: "",
                    title: "",
                    fromTime: null,
                    toTime: null,
                    commentType: null,
                    receive: null,
                    shippedStatus: null,//收货状态
                    status: null,
                    shopName: "",
                    userOrder:true
                },
                orderTab: [{
                    key: "-1",
                    text: "全部订单"
                },
                    {
                        key: "1",
                        text: "待付款"
                    },
                    {
                        key: "2",
                        text: "待发货"
                    },
                    {
                        key: "toReceive",
                        text: "待收货"
                    },
                    {
                        key: "toComment",
                        text: "待评价"
                    }
                ],
                activeTab: "-1",
                simpleSearch: false


            }
        },
        created() {
            this.loadGroup()
        },
        methods: {
            orderTabChange(key) {
                this.activeTab = key
                console.log(key)
                if (key === "toReceive") {
                    // 已发货 待收货
                    this.searchData.shippedStatus =null
                    this.searchData.receive = "0"

                    this.searchData.status = null;
                    this.searchData.commentType = null


                } else if (key !== "toComment") {
                    this.searchData.status = key;
                    this.searchData.shippedStatus = null
                    this.searchData.receive = null
                } else {
                    this.searchData.commentType = "0"
                    this.searchData.status = "5";
                    this.searchData.shippedStatus =null
                    this.searchData.receive = null
                }
                this.loadGroup()
            },
            moment,

            disabledStartDate(startValue) {
                const endValue = this.searchData.toTime;
                if (!startValue || !endValue) {
                    return false;
                }
                return startValue.valueOf() > endValue.valueOf();
            },
            disabledEndDate(endValue) {
                const startValue = this.searchData.fromTime;
                if (!endValue || !startValue) {
                    return false;
                }
                return startValue.valueOf() >= endValue.valueOf();
            },
            fromTimeChange(value) {
                this.searchData.fromTime = value.format("YYYY-MM-DD HH:mm:ss")
                this.loadGroup()
            },
            toTimeChange(value) {
                this.searchData.toTime = value.format("YYYY-MM-DD HH:mm:ss")
                this.loadGroup()
            },
            loadGroup() {
                orderApi.queryUserOrderList(this.pageMap.page, this.pageMap.size, this.searchData).then(resp => {
                    if (resp.data.flag) {
                        console.log(resp.data.data)
                        this.orderData = resp.data.data.rows;
                        this.pageMap.total = resp.data.data.total
                    }
                })
            },
            pageChange(current) {
                this.pageMap.page = current;
                this.loadGroup()
            },
            /**
             * 删除订单
             * @param orderShop
             */
            deleteOrder(orderShop) {
                console.log(orderShop)
                let status = orderShop.status;
                if (status && (status === 1 || status === 5 || status === 6)) {
                    let that = this;
                    this.$confirm({
                        title: '确定删除该订单吗？',
                        content: '删除订单后可在回收站找到，或进行永久删除',
                        onOk() {
                            orderApi.deleteOrder(orderShop.id).then(Resp => {
                                if (Resp.data.flag) {
                                    that.loadGroup();
                                }
                            })
                        },
                        onCancel() {
                        },
                    });
                } else {
                    this.$message.warning("订单进行中，不可删除");
                }

            },
            toGoodsDetail(goods) {
                console.log(goods)
                let selectedParam = JSON.parse(goods.spec)
                let indexesArr = Object.values(selectedParam)
                let indexes = ""
                indexesArr.forEach(item => {
                    indexes += item + "_"
                })
                let uri = `/goodDetail?goodsInfo=${encodeURI(JSON.stringify({
                    id: goods.goodsId,
                    index: indexes.substring(0, indexes.length - 1)
                }))}`
                console.log(indexes.substring(0, indexes.length - 1))
                this.$router.push(encodeURI(uri))
            },
            buyAgain() {
                this.$router.push("/cart_index")
            },
            /**
             * 收货
             * @param goods
             */
            reveiveGoods(goods) {
                console.log(goods)
                orderApi.receiveGoods(goods.id, goods.orderShopId).then(resp => {
                    if (resp.data.flag) {
                        this.$message.success(resp.data.message)
                        this.reload()
                    }
                })
            },
            /**
             * 到支付页
             * @param orderShop
             */
            toPay(orderShop) {
                this.$router.push(`/order_pay?orderId=${orderShop.orderId}`)

            },
            pubComment(goods) {
                console.log(goods)
                let info = {
                    orderId: goods.orderId,
                    skuId: goods.skuId,
                    goodsId: goods.goodsId,
                    spec: goods.specDisplayName,
                }
                let specIndex = ""
                if (goods.spec) {
                    let specStr = JSON.parse(goods.spec);
                    for (let key in specStr) {
                        specIndex += specStr[key] + "_"
                    }
                }
                specIndex = specIndex.substring(0, specIndex.length - 1)
                let goodsInfo = {}

                if (specIndex) {
                    goodsInfo = {id: info.goodsId, index: specIndex}
                } else {
                    goodsInfo = {id: info.goodsId}
                }
                let uri = `/goodDetail?goodsInfo=${encodeURI(JSON.stringify(goodsInfo))}&comment=${encodeURI(JSON.stringify(info))}`;
                this.$router.push(encodeURI(uri))
                console.log(uri)
            },

            exportOrder() {
                this.$message.success("正在导出")

                orderApi.exportOrder(this.searchData, this.pageMap.page, this.pageMap.size).then(resp => {

                    let contentDis = resp.headers['content-disposition'];
                    let fileName = contentDis.split(";")[1].split("=")[1].split(".")[0]
                    this.$fileDownload(resp.data, fileName + ".xlsx")
                })
            },


        }
    }
</script>

<style scoped>
    .order-shop-top {
        margin-right: 20px;
        font-size: 12px;
    }

    .table-header {
        background: #F9D2D3;
        padding: 15px 5px;
        background: #F5F5F5;
    }

    .order-card {
        border: 1px solid #ececec;
        padding: 5px 5px 0 5px;
        margin-bottom: 10px;
        cursor: pointer;
    }

    .order-item {
        margin-bottom: 10px;
        padding-bottom: 10px;
    }

    .goods-title {
        line-height: 16px;
        color: #3c3c3c;
        font-size: 12px;
        margin-bottom: 5px;
    }

    .goods-spec {
        font-size: 12px;
        color: #9e9e9e;
        margin-top: 10px;
    }

    .shopName {
        color: #3C3C3C;
    }

    .shopName :hover {
        color: red;
    }

    .delete-btn {
        font-size: 16px;
    }

    .delete-btn :hover {
        color: #E2231A;
    }
</style>
<style>


</style>
